// pages/humidity/humidity.js
const app = getApp()
let chart = null

Page({
  data: {
    humidity: 0,
    statusText: '正常',
    statusClass: 'normal',
    statusColor: '#52c41a',
    humidThresholdMax: 60,
    humidThresholdMin: 30,
    maxHumid: 0,
    minHumid: 0,
    avgHumid: 0,
    autoControl: false,
    lastUpdate: '未更新'
  },

  // 定时器ID
  refreshTimer: null,

  onLoad() {
    this.loadData()
    this.initChart()
    // 启动自动刷新
    this.startAutoRefresh()
  },

  onReady() {
    // 在页面准备完成后绘制图表
    setTimeout(() => {
      this.drawChart()
    }, 500)
  },

  onShow() {
    this.loadData()
    if (chart) {
      this.drawChart()
    }
    // 重启自动刷新
    this.startAutoRefresh()
  },

  onHide() {
    // 停止自动刷新
    this.stopAutoRefresh()
  },

  onUnload() {
    // 清理定时器
    this.stopAutoRefresh()
  },

  // 启动自动刷新
  startAutoRefresh() {
    this.stopAutoRefresh()
    this.refreshTimer = setInterval(() => {
      this.loadData()
      if (chart) {
        this.drawChart()
      }
    }, 2000) // 每2秒刷新一次（图表刷新频率可以低一些）
  },

  // 停止自动刷新
  stopAutoRefresh() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    }
  },

  // 加载数据
  loadData() {
    const deviceData = app.globalData.deviceData
    const humidStatus = app.getHumidStatus()
    
    // 计算统计数据
    const humids = app.globalData.humidityHistory.map(item => item.value)
    const maxHumid = Math.max(...humids)
    const minHumid = Math.min(...humids)
    const avgHumid = humids.reduce((a, b) => a + b, 0) / humids.length
    
    // 确定状态样式
    let statusClass = 'normal'
    let statusColor = '#52c41a'
    if (humidStatus.text === '湿度过高') {
      statusClass = 'danger'
      statusColor = '#ff4d4f'
    } else if (humidStatus.text === '湿度过低') {
      statusClass = 'warning'
      statusColor = '#faad14'
    }
    
    this.setData({
      humidity: deviceData.humidity.toFixed(1),
      statusText: humidStatus.text,
      statusClass: statusClass,
      statusColor: statusColor,
      humidThresholdMax: deviceData.humidThresholdMax,
      humidThresholdMin: deviceData.humidThresholdMin,
      maxHumid: maxHumid.toFixed(1),
      minHumid: minHumid.toFixed(1),
      avgHumid: avgHumid.toFixed(1),
      lastUpdate: deviceData.lastUpdate || '未更新'
    })
  },

  // 初始化图表
  initChart() {
    const ctx = wx.createCanvasContext('humidChart', this)
    chart = ctx
  },

  // 绘制图表
  drawChart() {
    if (!chart) return
    
    const history = app.globalData.humidityHistory
    const maxThreshold = app.globalData.deviceData.humidThresholdMax
    const minThreshold = app.globalData.deviceData.humidThresholdMin
    
    // 画布尺寸
    const query = wx.createSelectorQuery().in(this)
    query.select('.chart-container').boundingClientRect()
    query.exec((res) => {
      if (!res[0]) return
      
      const canvasWidth = res[0].width
      const canvasHeight = res[0].height
      const padding = 40
      const chartWidth = canvasWidth - padding * 2
      const chartHeight = canvasHeight - padding * 2
      
      // 清空画布
      chart.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 获取湿度范围
      const humids = history.map(item => item.value)
      const maxHumid = Math.max(...humids, maxThreshold)
      const minHumid = Math.min(...humids, minThreshold)
      const humidRange = maxHumid - minHumid
      
      // 绘制网格线
      chart.setStrokeStyle('#f0f0f0')
      chart.setLineWidth(1)
      for (let i = 0; i <= 4; i++) {
        const y = padding + (chartHeight / 4) * i
        chart.beginPath()
        chart.moveTo(padding, y)
        chart.lineTo(canvasWidth - padding, y)
        chart.stroke()
      }
      
      // 绘制阈值线
      const maxY = padding + chartHeight - ((maxThreshold - minHumid) / humidRange * chartHeight)
      const minY = padding + chartHeight - ((minThreshold - minHumid) / humidRange * chartHeight)
      
      // 最高阈值线
      chart.setStrokeStyle('#ff4d4f')
      chart.setLineWidth(2)
      chart.setLineDash([5, 5])
      chart.beginPath()
      chart.moveTo(padding, maxY)
      chart.lineTo(canvasWidth - padding, maxY)
      chart.stroke()
      
      // 最低阈值线
      chart.setStrokeStyle('#faad14')
      chart.beginPath()
      chart.moveTo(padding, minY)
      chart.lineTo(canvasWidth - padding, minY)
      chart.stroke()
      
      // 绘制湿度曲线
      chart.setLineDash([])
      chart.setStrokeStyle('#52c41a')
      chart.setLineWidth(3)
      chart.beginPath()
      
      history.forEach((item, index) => {
        const x = padding + (chartWidth / (history.length - 1)) * index
        const y = padding + chartHeight - ((item.value - minHumid) / humidRange * chartHeight)
        
        if (index === 0) {
          chart.moveTo(x, y)
        } else {
          chart.lineTo(x, y)
        }
      })
      
      chart.stroke()
      
      // 绘制数据点
      chart.setFillStyle('#52c41a')
      history.forEach((item, index) => {
        const x = padding + (chartWidth / (history.length - 1)) * index
        const y = padding + chartHeight - ((item.value - minHumid) / humidRange * chartHeight)
        
        chart.beginPath()
        chart.arc(x, y, 4, 0, 2 * Math.PI)
        chart.fill()
      })
      
      // 绘制Y轴标签
      chart.setFillStyle('#999999')
      chart.setFontSize(10)
      for (let i = 0; i <= 4; i++) {
        const humid = minHumid + (humidRange / 4) * (4 - i)
        const y = padding + (chartHeight / 4) * i
        chart.fillText(humid.toFixed(1) + '%', 5, y + 4)
      }
      
      chart.draw()
    })
  },

  // 设置最高阈值
  setMaxThreshold() {
    wx.showModal({
      title: '设置最高湿度阈值',
      editable: true,
      placeholderText: '请输入湿度值（%）',
      content: String(this.data.humidThresholdMax),
      success: (res) => {
        if (res.confirm && res.content) {
          const value = parseFloat(res.content)
          if (isNaN(value)) {
            wx.showToast({
              title: '请输入有效数字',
              icon: 'none'
            })
            return
          }
          if (value <= this.data.humidThresholdMin) {
            wx.showToast({
              title: '最高湿度必须大于最低湿度',
              icon: 'none'
            })
            return
          }
          
          app.globalData.deviceData.humidThresholdMax = value
          app.saveConfig()
          this.setData({
            humidThresholdMax: value
          })
          this.loadData()
          this.drawChart()
          
          // 发送MQTT消息（所有字段都为数字类型）
          const deviceData = app.globalData.deviceData
          const message = {
            fd: parseInt(deviceData.deviceFd) || 0,  // 设备fd转为int
            Tem_max: deviceData.tempThresholdMax,    // 数字类型
            Tem_min: deviceData.tempThresholdMin,    // 数字类型
            Hum_max: value,                          // 数字类型
            Hum_min: deviceData.humidThresholdMin,   // 数字类型
            food: deviceData.foodAmount              // 数字类型
          }
          
          app.sendMQTTMessage(message).then(() => {
            wx.showToast({
              title: '设置并发送成功',
              icon: 'success'
            })
          }).catch(() => {
            wx.showToast({
              title: '设置成功',
              icon: 'success'
            })
          })
        }
      }
    })
  },

  // 设置最低阈值
  setMinThreshold() {
    wx.showModal({
      title: '设置最低湿度阈值',
      editable: true,
      placeholderText: '请输入湿度值（%）',
      content: String(this.data.humidThresholdMin),
      success: (res) => {
        if (res.confirm && res.content) {
          const value = parseFloat(res.content)
          if (isNaN(value)) {
            wx.showToast({
              title: '请输入有效数字',
              icon: 'none'
            })
            return
          }
          if (value >= this.data.humidThresholdMax) {
            wx.showToast({
              title: '最低湿度必须小于最高湿度',
              icon: 'none'
            })
            return
          }
          
          app.globalData.deviceData.humidThresholdMin = value
          app.saveConfig()
          this.setData({
            humidThresholdMin: value
          })
          this.loadData()
          this.drawChart()
          
          // 发送MQTT消息（所有字段都为数字类型）
          const deviceData = app.globalData.deviceData
          const message = {
            fd: parseInt(deviceData.deviceFd) || 0,  // 设备fd转为int
            Tem_max: deviceData.tempThresholdMax,    // 数字类型
            Tem_min: deviceData.tempThresholdMin,    // 数字类型
            Hum_max: deviceData.humidThresholdMax,   // 数字类型
            Hum_min: value,                          // 数字类型
            food: deviceData.foodAmount              // 数字类型
          }
          
          app.sendMQTTMessage(message).then(() => {
            wx.showToast({
              title: '设置并发送成功',
              icon: 'success'
            })
          }).catch(() => {
            wx.showToast({
              title: '设置成功',
              icon: 'success'
            })
          })
        }
      }
    })
  },

  // 自动控制开关
  onAutoControlChange(e) {
    const checked = e.detail.value
    this.setData({
      autoControl: checked
    })
    
    wx.showToast({
      title: checked ? '已开启自动调节' : '已关闭自动调节',
      icon: 'success'
    })
  },

  // 刷新数据
  onRefresh() {
    wx.showLoading({
      title: '刷新中...'
    })
    
    // 重新加载真实数据
    this.loadData()
    this.drawChart()
    
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      })
    }, 500)
  },

  // 重置阈值
  onReset() {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置湿度阈值为默认值吗？',
      success: (res) => {
        if (res.confirm) {
          app.globalData.deviceData.humidThresholdMax = 60
          app.globalData.deviceData.humidThresholdMin = 30
          app.saveConfig()
          
          this.setData({
            humidThresholdMax: 60,
            humidThresholdMin: 30
          })
          
          this.loadData()
          this.drawChart()
          
          wx.showToast({
            title: '重置成功',
            icon: 'success'
          })
        }
      }
    })
  }
})

